package com.ledi.guns.common.persistence.page;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.core.annotation.AnnotationUtils;

import com.ledi.guns.common.util.StringUtil;

public class PageQuery<T> {

	public static final Integer defaultPageSize = 10;

	private Integer pageNo = 1;

	private Integer pageSize = defaultPageSize;

	private String orderBy;

	private OrderType orderType = OrderType.DESC;

	public Map<String, Object> getSearch() {

		Map<String, Object> map = new HashMap<>();
		Class<? extends PageQuery> class1 = this.getClass();
		Field[] fields = FieldUtils.getAllFields(class1);
		for (Field field : fields) {
			Object object = null;
			try {
				object = FieldUtils.readField(this, field.getName(), true);
			} catch (IllegalAccessException e) {
			}
			Class<?> type = field.getType();
			if (type.isAssignableFrom(String.class)) {
				if (object != null) {
					object = ((String) object).trim();
					if (StringUtil.isBlank((String) object)) {
						object = null;
					}
				}
			}

			map.put(field.getName(), object);
		}

		return map;
	}

	/**
	 * 获取当前页码
	 *
	 * @return
	 */
	public int getPageNo() {

		return pageNo;
	}

	/**
	 * 设置当前页码
	 *
	 * @param pageNo
	 */
	public void setPageNo(int pageNo) {

		this.pageNo = pageNo;
	}

	/**
	 * 获取页面大小
	 *
	 * @return
	 */
	public int getPageSize() {

		return pageSize;
	}

	/**
	 * 设置页面大小（最大500）
	 *
	 * @param pageSize
	 */
	public void setPageSize(int pageSize) {

		this.pageSize = pageSize <= 0 ? defaultPageSize : pageSize;// > 500 ? 500 : pageSize;
	}

	public String getOrderBy() {

		if (StringUtil.isBlank(orderBy)) {
			orderBy = "id";
		}
		return orderBy;
	}

	public void setOrderBy(String orderBy) {// throws Exception {

		if (StringUtil.isBlank(orderBy)) {
			orderBy = "id";
		}
		this.orderBy = orderBy;
	}

	public OrderType getOrderType() {

		return orderType;
	}

	public void setOrderType(OrderType orderType) {

		this.orderType = orderType;
	}

	public void checkOrder(Class<T> clazz) {

		DefaultOrderBy annotation = AnnotationUtils.findAnnotation(clazz, DefaultOrderBy.class);
		// 没有注解就用默认的
		if (annotation == null) {
			if (StringUtil.isEmpty(orderBy)) {
				orderBy = (String) AnnotationUtils.getDefaultValue(DefaultOrderBy.class);
			}
			if (orderType == null) {
				orderType = (OrderType) AnnotationUtils.getDefaultValue(DefaultOrderBy.class, "orderType");
			}
		} else {
			if (StringUtil.isEmpty(this.orderBy)) {
				this.orderBy = annotation.value();
			}
			if (orderType == null) {
				orderType = annotation.orderType();
			}
		}
		// orderBy需要对应具体列
		Field field = FieldUtils.getField(clazz, orderBy, true);
		if (field == null) {
			this.orderBy = null;
		} else {
			getSearch().put("orderBy", StringUtil.humpToLine(orderBy));
			getSearch().put("orderType", orderType.name());
		}

	}
}
